package com.jf.cloud.order.config.sharding;

import com.jf.cloud.order.constant.OrderShardingTableType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 分片策略辅助组件
 * @author zz
 * @version 1.0
 */
@Component
public class ShardingAlgorithmHelper {

    /**
     * 总的分库数量  默认8
     */
    protected static int DATABASE_SIZE;

    /**
     * 每个库的分表数量 默认64
     */
    protected static int TABLE_SIZE;

    /**
     * 退款表的分表数量 默认32
     */
    protected static int REFUND_TABLE_SIZE;

    /**
     * 退款表的分表数量 默认32
     */
    protected static int PURCHASE_TABLE_SIZE;

    @Value("${spring.shardingsphere.database.default.size:8}")
    public void setDatabaseSize(int databaseSize) {
        DATABASE_SIZE = databaseSize;
    }

    @Value("${spring.shardingsphere.table.default.size:64}")
    public void setTableSize(int tableSize) {
        TABLE_SIZE = tableSize;
    }
    @Value("${spring.shardingsphere.table.refund.size:32}")
    public void setRefundTableSize(int refundTableSize) {
        REFUND_TABLE_SIZE = refundTableSize;
    }
    @Value("${spring.shardingsphere.table.purchase.size:2}")
    public void setPurchaseTableSize(int purchaseTableSize) {
        PURCHASE_TABLE_SIZE = purchaseTableSize;
    }

    /**
     * 计算database的后缀
     * @param valueSuffix 分片键的值后三位
     * @return 数据源名后缀
     */
    public static String getDatabaseSuffix(int valueSuffix) {
        return valueSuffix % DATABASE_SIZE + "";
    }

    /**
     * 计算table的后缀
     * @param valueSuffix 分片键的值后三位
     * @return 表名后缀
     */
    public static String getTableSuffix(int valueSuffix, OrderShardingTableType orderShardingTableType) {
        if (Objects.equals(orderShardingTableType, OrderShardingTableType.REFUND)) {
            return "_" + (valueSuffix / DATABASE_SIZE) % REFUND_TABLE_SIZE;
        } else if (Objects.equals(orderShardingTableType, OrderShardingTableType.PURCHASE)) {
            return "_" + (valueSuffix / DATABASE_SIZE) % PURCHASE_TABLE_SIZE;
        }
        return "_" + (valueSuffix / DATABASE_SIZE) % TABLE_SIZE;
    }

}
